package com.thinkit.cms.service.resource;

import com.google.common.collect.Lists;
import com.thinkit.cms.api.resource.SysFileGroupService;
import com.thinkit.cms.dto.resource.SysFileGroupDto;
import com.thinkit.cms.entity.resource.SysFileGroup;
import com.thinkit.cms.mapper.resource.SysFileGroupMapper;
import com.thinkit.core.base.BaseServiceImpl;
import com.thinkit.core.handler.CustomException;
import com.thinkit.utils.model.ApiResult;
import com.thinkit.utils.utils.Checker;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sysFileGroup
 * @since 2021-07-03
 */
@Transactional
@Service
public class SysFileGroupServiceImpl extends BaseServiceImpl<SysFileGroupDto, SysFileGroup, SysFileGroupMapper> implements SysFileGroupService {


    @Override
    public List<String> listGroupIds() {
        List<String> gids = baseMapper.listGroupIds(getSiteId());
        return Checker.BeNotEmpty(gids) ? gids: Lists.newArrayList();
    }

    @Override
    public List<SysFileGroupDto> listGroupName(SysFileGroupDto v) {
        List<SysFileGroupDto> lists = new ArrayList<>();
        SysFileGroupDto allGroup = new SysFileGroupDto();
        allGroup.setCode("ALL").setIsSysGroup(1).setName("全部").setId("-1");
        lists.add(allGroup);

        List<SysFileGroupDto> sysFileGroupDtos = baseMapper.listGroupName(v);
        sysFileGroupDtos = Checker.BeNotEmpty(sysFileGroupDtos)?sysFileGroupDtos:Lists.newArrayList();
        int allCount =0;
        for(SysFileGroupDto fileGroupDto:sysFileGroupDtos){
            allCount+=fileGroupDto.getFileCount();
        }
        lists.addAll(sysFileGroupDtos);
        allGroup.setFileCount(allCount);
        return lists;
    }

    @Override
    public ApiResult addGroup(SysFileGroupDto v) {
        int count = baseMapper.hasName(v.getName(),v.getSiteId(),null);
        if(count>0){
            return ApiResult.result(20049);
        }
        super.insert(v);
        return ApiResult.result();
    }

    @Transactional
    @Override
    public ApiResult deleteGroup(String id) {
        baseMapper.updateToNoGid(id);
        super.deleteByPk(id);
        return ApiResult.result();
    }

    @Override
    public ApiResult updateFileGid(String fileId, String gid) {
        if(Checker.BeNotBlank(gid)){
            baseMapper.updateFileGid(fileId,gid);
        }
        return ApiResult.result();
    }

    @Override
    public void renameGroup(SysFileGroupDto v) {
        int count = baseMapper.hasName(v.getName(),v.getSiteId(),v.getId());
        if(count>0){
            throw new CustomException( ApiResult.result(20049));
        }
        super.updateByPk(v);
    }
}
